package com.zhuyi.broadcast.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuyi.broadcast.mapper.AuditRecordMapper;
import com.zhuyi.broadcast.mapper.AuditTaskMapper;
import com.zhuyi.broadcast.mapper.ScheduleMapper;
import com.zhuyi.broadcast.pojo.domain.*;
import com.zhuyi.broadcast.service.AuditService;
import com.zhuyi.broadcast.service.WebSocketService;
import com.zhuyi.common.constant.BroadcastConstants;
import com.zhuyi.common.core.domain.AjaxResult;
import com.zhuyi.common.utils.DateUtils;
import com.zhuyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.zhuyi.common.core.domain.AjaxResult.error;
import static com.zhuyi.common.core.domain.AjaxResult.success;


/**
 * <p>
 *  审核实现类
 * </p>
 *
 * @author dyj
 * @since 2024-12-24
 */
@Service
public class AuditServiceImpl extends ServiceImpl<AuditTaskMapper, AuditTask> implements AuditService {

    @Autowired
    private AuditTaskMapper auditTaskMapper;

    @Autowired
    private AuditRecordMapper auditRecordMapper;

    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private AuditService auditService;

    @Autowired
    private ScheduleMapper scheduleMapper;

    /**
     * 提交审核任务
     * @param auditTask
     * @return
     */
    public AjaxResult submitAuditTask(AuditTask auditTask) {
        // 使用 LambdaQueryWrapper 来构建查询条件
        LambdaQueryWrapper<AuditTask> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AuditTask::getTaskName, auditTask.getTaskName());

        // 查询是否存在相同资源的待审核任务
        AuditTask existingTask = auditTaskMapper.selectOne(queryWrapper);

        if (existingTask != null) {
            // 任务已存在，检查审核结果
            LambdaQueryWrapper<AuditRecord> recordWrapper = Wrappers.lambdaQuery();
            recordWrapper.eq(AuditRecord::getTaskId, existingTask.getId())
                    .orderByDesc(AuditRecord::getAuditTime);
            AuditRecord lastRecord_record = auditRecordMapper.selectOne(recordWrapper);

            LambdaQueryWrapper<AuditTask> taskWrapper = Wrappers.lambdaQuery();
            taskWrapper.eq(AuditTask::getTaskName, existingTask.getTaskName())
                    .orderByDesc(AuditTask::getCreateTime);
            AuditTask lastRecord_task = auditTaskMapper.selectOne(taskWrapper);

            if (lastRecord_task != null && BroadcastConstants.RESOURCE_STATE_rejected.equals(lastRecord_task.getStatus())) {
                return error("上次审核未通过，原因是：" + lastRecord_record.getComments() + "请确认后重新提交。");
            }

            if (BroadcastConstants.RESOURCE_STATE_APPROVED.equals(existingTask.getStatus())) {
                return error("该资源已审核通过，无法再次提交审核。");
            }
        }

        // 正常提交审核任务
        auditTask.setCreateTime(DateUtils.getNowDate());
        auditTask.setSubmitterId(SecurityUtils.getLoginUser().getUserId());
        save(auditTask);  // 使用 IService 提供的 save 方法
        webSocketService.notifyAllUsers("有新的审核任务提交");
        return success("审核任务提交成功");
    }

    /**
     * 审核任务
     * @param taskId
     * @param auditorId
     * @param result
     * @param comments
     * @return
     */
    @Override
    public AjaxResult auditTask(Long taskId, Long auditorId, String result, String comments) {
        // 使用 LambdaQueryWrapper 构建条件查询
        LambdaQueryWrapper<AuditTask> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AuditTask::getId, taskId);
        AuditTask auditTask = auditTaskMapper.selectOne(queryWrapper);

        if (auditTask == null) {
            return error("任务未找到");
        }

        if (!BroadcastConstants.RESOURCE_STATE_PENDING.equals(auditTask.getStatus())) {
            return error("任务已审核");
        }

        // 创建审核记录
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setTaskId(taskId);
        auditRecord.setAuditorId(auditorId);
        auditRecord.setResult(result);
        auditRecord.setComments(comments);
        auditRecordMapper.insert(auditRecord);

        // 更新任务状态
        auditTask.setStatus(result.equals(BroadcastConstants.RESOURCE_STATE_APPROVED) ?
                BroadcastConstants.RESOURCE_STATE_APPROVED : BroadcastConstants.RESOURCE_STATE_rejected);
        updateById(auditTask);  // 使用 IService 提供的 updateById 方法

        // WebSocket 通知
        webSocketService.notifyAllUsers("审核任务状态已更新，任务ID: " + taskId);
        return success("审核结果已提交");
    }

    /**
     * 获取未审核任务列表
     * @return
     */
    @Override
    public List<AuditTask> getPendingTasks() {
        LambdaQueryWrapper<AuditTask> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AuditTask::getStatus, BroadcastConstants.RESOURCE_STATE_PENDING);
        return auditTaskMapper.selectList(queryWrapper);
    }

    /**
     * 获取所有审核任务
     * @return
     */
    public List<AuditTask> list(AuditTask auditTask) {
        LambdaQueryWrapper<AuditTask> wrapper = new LambdaQueryWrapper<>();
        // 如果 program 中的属性为空，查询所有数据
        return baseMapper.selectList(wrapper);
    }

    // 创建并提交审核任务(公共方法)
    public void createAndSubmitAuditTask(Object taskObject, String taskType) {
        AuditTask auditTask = new AuditTask();

        // 根据传入的对象类型来设置任务的内容
        if (taskObject instanceof Resource) {
            Resource resource = (Resource) taskObject;
            auditTask.setStatus(resource.getResourceState());
            auditTask.setContentId(resource.getId());
            auditTask.setTaskName(resource.getResourceName());
            auditTask.setTask_Type(resource.getResourceType());
        } else if (taskObject instanceof Schedule) {
            Schedule schedule = (Schedule) taskObject;
            auditTask.setStatus(schedule.getState());
            auditTask.setContentId(schedule.getId());
            auditTask.setTaskName(schedule.getScheduleName());
            auditTask.setTask_Type("轮播计划");
        }else if (taskObject instanceof InsertBroadcastTask) {
            InsertBroadcastTask insertBroadcastTask = (InsertBroadcastTask) taskObject;
            auditTask.setStatus(insertBroadcastTask.getStatus());
            auditTask.setContentId(insertBroadcastTask.getScheduleId());
            auditTask.setTaskName(scheduleMapper.selectById(insertBroadcastTask.getScheduleId()).getScheduleName());
            auditTask.setTask_Type("插播计划");
        }

        // 提交审核任务
        auditService.submitAuditTask(auditTask);
    }

}


